package com.wejoy.video.middle.station.api.controller.dept;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wejoy.video.middle.station.api.annotation.LoginCheck;
import com.wejoy.video.middle.station.data.domain.system.SysDept;
import com.wejoy.video.middle.station.data.domain.system.SysUser;
import com.wejoy.video.middle.station.data.service.evs.IEvsHttpService;
import com.wejoy.video.middle.station.data.service.system.ISysDeptService;
import com.wejoy.video.middle.station.data.util.LoginUtil;
import com.wejoy.video.middle.station.data.util.baiduevs.EvsApiHttpUtils;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import com.wejoy.video.middle.station.data.vo.api.DeptNode;
import com.wejoy.video.middle.station.data.vo.api.DeptPointVO;
import org.ehcache.core.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/dept")
public class DeptAction {

    @Autowired
    private IEvsHttpService evsHttpService;
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取部门树
     * @param loginSysUser
     * @return
     * @throws IOException
     */
    @ResponseBody
    @LoginCheck
    @GetMapping("/getDeptTree")
    public RespJSON getDeptTree(Integer parentId,Boolean includeLower,@SessionAttribute(value = LoginUtil.LOGIN_USER_SESSION_KEY) SysUser loginSysUser){
        SysDept evsApiDept = new SysDept();
        evsApiDept.setParentId(parentId);
        evsApiDept.setIncludeLower(includeLower==null?false:includeLower);
        List<DeptPointVO> deptPointVOS = JSONArray.parseArray(JSONObject.toJSONString(evsHttpService.getDepartmentsJson(evsApiDept, loginSysUser.getToken())), DeptPointVO.class);
        if(CollectionUtils.isEmpty(deptPointVOS)){
            return RespJSON.success(deptPointVOS);
        }
        for (DeptPointVO datum : deptPointVOS) {
            JSONObject points = evsHttpService.getPoints(loginSysUser.getToken(), 1, 1, datum.getId(),null,null);
            if(CollectionUtils.isEmpty(points.getJSONArray("data"))){
                datum.setCheckPoint(false);
            }else {
                datum.setCheckPoint(true);
            }
        }
        return RespJSON.success(deptPointVOS);
    }
}
